package com.levenx.authModel.service.support;

import com.levenx.authModel.dao.MenuRepository;
import com.levenx.authModel.model.Menu;
import com.levenx.authModel.service.MenuService;
import com.levenx.vo.MenuNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DefaultMenuServcieImpl implements MenuService {

    @Autowired
    private MenuRepository menuRepository;

    @Override
    public List<MenuNode> initMenu() {
        List<Menu> menus = menuRepository.findAll();
        List<Menu> prentMenus =
                menus.stream().filter(note -> null == note.getPid()).collect(Collectors.toList());
        menus.removeAll(prentMenus);
        List<MenuNode> topNodes = prentMenus
                .stream().map(item ->
                        new MenuNode().id(item.getId()).pid(item.getPid()).path(item.getPath())
                                .name(item.getName()).icon(item.getIcon()).redirect(item.getRedirect())).collect(Collectors.toList());
        List<MenuNode> childrenNodes = menus
                .stream().map(item ->
                        new MenuNode().id(item.getId()).pid(item.getPid()).path(item.getPath())
                                .name(item.getName()).icon(item.getIcon()).redirect(item.getRedirect())).collect(Collectors.toList());
        return initMenus(topNodes,childrenNodes);
    }


    private List<MenuNode> initMenus(List<MenuNode> topNodes, List<MenuNode> childNodes){
        for (MenuNode topNote : topNodes) {
            for (MenuNode childNote : childNodes) {
                if(childNote.getPid()==topNote.getId()){
                    topNote.getChildren().add(childNote);
                }
            }
        }
        return topNodes;
    }
}
